<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This is a sample module for PyroCMS
 *
 * @author 		Jerel Unruh - PyroCMS Dev Team
 * @website		http://unruhdesigns.com
 * @package 	PyroCMS
 * @subpackage 	Sample Module
 */
class Admin extends Admin_Controller
{
	protected $section = 'discounts';
	protected $_ci;
	public function __construct()
	{
		parent::__construct();
		$this->_ci = &get_instance();
		// Load all the required classes
		$this->load->library('form_validation');
		$this->load->model('escort_discount_tickets_m');
		$this->lang->load('discount');
		// Set the validation rules
		$this->validation_rules = array(
		array(
				'field' => 'discount_code',
				'label' => 'lang:escort_be_discount_discount_code_label',
				'rules' => 'trim|max_length[255]|alpha_dash|required|callback__check_code'
				),
				array(
				'field'	=> 'discount_type_code',
				'label'	=> 'lang:escort_be_discount_discount_type_label'
				),
				array(
				'field' => 'description',
				'label' => 'lang:escort_be_discount_description_label',
				'rules' => 'trim'
				),
				array(
				'field' => 'active',
				'label' => 'lang:escort_be_discount_active_label',
				'rules' => 'trim'
				)
				);
				$this->data->discountTypeList = array();

				$discountTypes = $this->_ci->discount_type_entity->getList();
				if($discountTypes){
					foreach ( $discountTypes as $discountType){
						$this->data->discountTypeList[$discountType->id] = $discountType->name;
					}
				}

				$this->template->set_partial('shortcuts', 'admin/partials/shortcuts')
				->append_metadata(js('escort.discount.js', 'be_discount'))
				->append_metadata(css('escort.discount.css', 'be_discount'));
	}

	/**
	 * List all items
	 */
	public function index()
	{
		// Create pagination links
		$total_rows = $this->_ci->discount_ticket_entity->count();
		$pagination = create_pagination('admin/be_discount/index', $total_rows);
		// Using this data, get the relevant results
		$discounts = $this->_ci->discount_ticket_entity->getList($pagination['limit']);

		//do we need to unset the layout because the request is ajax?
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';

		$this->template
		->title($this->module_details['name'])
		->append_metadata(js('admin/filter.js'))
		->set('pagination', $pagination)
		->set('discounts', $discounts);

		$this->input->is_ajax_request() ? $this->template->build('admin/tables/posts', $this->data) : $this->template->build('admin/index', $this->data);
			
	}

	public function create()
	{
		$this->form_validation->set_rules($this->validation_rules);

		if ($this->form_validation->run())
		{
			$id = $this->escort_discount_tickets_m->insert(array(
				'discount_code'	=> $this->input->post('discount_code'),
				'discount_type_code'	=> $this->input->post('discount_type_code'),
				'description'	=> $this->input->post('description'),
				'active'	=> $this->input->post('active'),
				'created_time'	=> time()
			));
			
			$this->session->set_flashdata('success', sprintf($this->lang->line('blog_post_add_success'), $this->input->post('title')));
			do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_create_discount_action', array($this->input->post('discount_code')));
			
			$this->input->post('btnAction') == 'save_exit' ? redirect('admin/be_discount') : redirect('admin/be_discount/edit/' . $id);
		}
		else
		{
			// Go through all the known fields and get the post values
			foreach ($this->validation_rules as $key => $field)
			{
				$discount->$field['field'] = set_value($field['field']);
			}
		}

		$this->template
		->title($this->module_details['name'], lang('escort_be_discount_type_add_title'))
		->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
		->append_metadata(js('jquery/jquery.tagsinput.min.js'))
		->append_metadata(js('blog_form.js', 'blog'))
		->append_metadata(css('jquery/jquery.tagsinput.css'))
		->set('discount', $discount)
		->build('admin/form', $this->data);
	}
	public function edit($id = 0)
	{
		$id OR redirect('admin/be_discount');
		$discount = $this->escort_discount_tickets_m->get($id);
		$discount OR redirect('admin/be_discount');
		$this->form_validation->set_rules($this->validation_rules);
		if ($this->form_validation->run())
		{
			$result = $this->escort_discount_tickets_m->update($id, array(
					'discount_type_code'	=> $this->input->post('discount_type_code'),
					'description'	=> $this->input->post('description'),
					'active'	=> $this->input->post('active')
			));

			if ($result)
			{
				$this->session->set_flashdata(array('success' => sprintf(lang('escort_be_discount_edit_success'), $id)));
				do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_edit_discount_action', array($id));
			}
			else
			{
				$this->session->set_flashdata('error', $this->lang->line('escort_be_discount_edit_error'));
			}

			// Redirect back to the form or main page
			$this->input->post('btnAction') == 'save_exit' ? redirect('admin/be_discount') : redirect('admin/be_discount/edit/' . $id);
		}

		// Go through all the known fields and get the post values
		foreach ($this->validation_rules as $key => $field)
		{
			if (isset($_POST[$field['field']]))
			{
				$discount->$field['field'] = set_value($field['field']);
			}
		}

		$this->template
		->title($this->module_details['name'], sprintf(lang('escort_be_discount_edit_title'), $discount->discount_code))
		->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
		->append_metadata(js('jquery/jquery.tagsinput.min.js'))
		->append_metadata(js('blog_form.js', 'blog'))
		->append_metadata(css('jquery/jquery.tagsinput.css'))
		->set('discount', $discount)
		->build('admin/form');
	}
	public function delete($id = 0)
	{
		// Delete one
		$ids = ($id) ? array($id) : $this->input->post('action_to');

		// Go through the array of slugs to delete
		if ( ! empty($ids))
		{
			$discountCodes = array();
			foreach ($ids as $id)
			{
				// Get the current page so we can grab the id too
				if ($discount = $this->escort_discount_tickets_m->get($id))
				{
					$this->escort_discount_tickets_m->delete($id);
					do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_delete_discount_action', array($id));
					// Wipe cache for this model, the content has changed
					$this->pyrocache->delete('escort_discount_tickets_m');
					$discountCodes[] = $discount->discount_code;
				}
			}
		}

		// Some pages have been deleted
		if ( ! empty($discountCodes))
		{
			// Only deleting one page
			if (count($discountCodes) == 1)
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('escort_be_discount_delete_success'), $discountCodes[0]));
			}
			// Deleting multiple pages
			else
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('escort_be_discount_mass_delete_success'), implode('", "', $discountCodes)));
			}
		}
		// For some reason, none of them were deleted
		else
		{
			$this->session->set_flashdata('notice', lang('escort_be_discount_delete_error'));
		}

		redirect('admin/be_discount');
	}
	public function action()
	{
		switch ($this->input->post('btnAction'))
		{			
			case 'delete':
				$this->delete();
				break;
			default:
				redirect('admin/be_discount');
			break;
		}
	}
	public function _check_code($code)
	{
		$this->form_validation->set_message('_check_code', sprintf(lang('escort_be_discount_discount_code_exist_error'), lang('escort_be_discount_title')));
		if($this->escort_discount_tickets_m->get($code)){
			return false;
		}else{
			return true;
		}
	}
	public function generate_code(){
		$length = 6;
		$validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ1234567890";
		$validCharNumber = strlen($validCharacters);
		$result = "";
		for ($i = 0; $i < $length; $i++) {
			$index = mt_rand(0, $validCharNumber - 1);
			$result .= $validCharacters[$index];
		}
		if($this->_check_code($result)){
			$data = array('code' => $result);
			echo json_encode($data);
			return;
		}else{
			$this->generate_code();
		}
	}
}
